import easygui as eg
from database import Database


def show_guide_management(db, current_user):
    while True:
        # 获取导游列表
        guides = db.execute_query("""
            SELECT g.GuideID, u.RealName, g.LicenseNumber, 
                   g.Gender, g.Age, g.Experience,
                   CASE WHEN u.Status = 1 THEN '启用' ELSE '禁用' END AS StatusText
            FROM Guides g
            JOIN Users u ON g.UserID = u.UserID
            ORDER BY u.RealName
        """)

        if not guides:
            eg.msgbox("没有导游数据", "导游管理")
            break

        # 格式化显示
        guide_list = [
            f"ID:{g['GuideID']} | 姓名:{g['RealName']} | 导游证:{g['LicenseNumber']} | "
            f"性别:{g['Gender'] or '无'} | 状态:{g['StatusText']}"
            for g in guides
        ]

        # 添加操作选项
        guide_list.extend(["", "=== 操作选项 ===", "1. 查看详情", "2. 审核导游", "3. 编辑信息", "4. 返回"])

        choice = eg.choicebox("导游管理系统", "导游管理", guide_list)

        if not choice or choice == "4. 返回":
            break

        if choice == "1. 查看详情":
            guide_id = get_id_from_choice(choice)
            if guide_id:
                view_guide_details(db, guide_id)
        elif choice == "2. 审核导游":
            guide_id = get_id_from_choice(choice)
            if guide_id:
                review_guide(db, guide_id)
        elif choice == "3. 编辑信息":
            guide_id = get_id_from_choice(choice)
            if guide_id:
                edit_guide_info(db, guide_id)


def get_id_from_choice(choice):
    if "ID:" not in choice:
        return None
    return int(choice.split("ID:")[1].split("|")[0].strip())


def view_guide_details(db, guide_id):
    # 获取导游详细信息
    guide = db.execute_query("""
        SELECT g.*, u.Username, u.RealName, u.Email, u.Phone, u.Status
        FROM Guides g
        JOIN Users u ON g.UserID = u.UserID
        WHERE g.GuideID = ?
    """, (guide_id,))[0]

    # 获取负责的旅游团
    groups = db.execute_query("""
        SELECT tg.GroupID, tg.GroupName, tr.RouteName, 
               tg.StartDate, tg.EndDate, tg.Status
        FROM TravelGroups tg
        JOIN TravelRoutes tr ON tg.RouteID = tr.RouteID
        WHERE tg.GuideID = ?
    """, (guide_id,))

    # 构建显示信息
    info = f"=== 基本信息 ===\n"
    info += f"用户名: {guide['Username']}\n"
    info += f"真实姓名: {guide['RealName']}\n"
    info += f"导游证号: {guide['LicenseNumber']}\n"
    info += f"性别: {guide['Gender'] or '无'}\n"
    info += f"年龄: {guide['Age'] or '无'}\n"
    info += f"从业年限: {guide['Experience'] or '无'}\n"
    info += f"联系电话: {guide['Phone'] or '无'}\n"
    info += f"电子邮箱: {guide['Email'] or '无'}\n"
    info += f"状态: {'启用' if guide['Status'] else '禁用'}\n\n"
    info += f"=== 专长 ===\n{guide['Specialty'] or '无'}\n\n"
    info += f"=== 简介 ===\n{guide['Introduction'] or '无'}\n\n"

    if groups:
        info += "=== 负责的旅游团 ===\n"
        for g in groups:
            info += (
                f"团ID: {g['GroupID']} | 团名: {g['GroupName']} | "
                f"线路: {g['RouteName']}\n"
                f"出发: {g['StartDate'].strftime('%Y-%m-%d')} | "
                f"结束: {g['EndDate'].strftime('%Y-%m-%d')} | "
                f"状态: {get_group_status(g['Status'])}\n\n"
            )
    else:
        info += "=== 暂无负责的旅游团 ===\n"

    eg.textbox("导游详细信息", "导游详情", info)


def get_group_status(status):
    status_map = {
        'pending': '待确认',
        'confirmed': '已确认',
        'completed': '已完成',
        'cancelled': '已取消'
    }
    return status_map.get(status, status)


def review_guide(db, guide_id):
    # 获取当前状态
    status = db.execute_query("""
        SELECT u.Status FROM Users u
        JOIN Guides g ON u.UserID = g.UserID
        WHERE g.GuideID = ?
    """, (guide_id,))[0]['Status']

    if status:
        eg.msgbox("该导游已通过审核", "提示")
        return

    choices = ["通过审核", "拒绝审核"]
    choice = eg.buttonbox("审核导游", "导游审核", choices)

    if not choice:
        return

    try:
        new_status = 1 if choice == "通过审核" else 0
        db.execute_query("""
            UPDATE Users SET Status = ?
            WHERE UserID = (SELECT UserID FROM Guides WHERE GuideID = ?)
        """, (new_status, guide_id), False)

        eg.msgbox(f"已{choice}", "成功")
    except Exception as e:
        eg.msgbox(f"审核失败: {str(e)}", "错误")


def edit_guide_info(db, guide_id):
    # 获取当前信息
    guide = db.execute_query("""
        SELECT g.*, u.RealName, u.Email, u.Phone, u.Status
        FROM Guides g
        JOIN Users u ON g.UserID = u.UserID
        WHERE g.GuideID = ?
    """, (guide_id,))[0]

    fields = [
        "导游证号*", "性别", "年龄", "从业年限",
        "联系电话", "电子邮箱", "专长", "简介", "状态(1启用/0禁用)"
    ]
    values = [
        guide['LicenseNumber'],
        guide['Gender'] or "",
        str(guide['Age']) if guide['Age'] else "",
        str(guide['Experience']) if guide['Experience'] else "",
        guide['Phone'] or "",
        guide['Email'] or "",
        guide['Specialty'] or "",
        guide['Introduction'] or "",
        str(guide['Status'])
    ]

    new_values = eg.multenterbox(f"编辑导游信息: {guide['RealName']}", "导游编辑", fields, values)

    if not new_values:
        return

    # 验证必填字段
    if not new_values[0]:
        eg.msgbox("导游证号为必填项", "错误")
        return

    try:
        # 更新导游表
        db.execute_query("""
            UPDATE Guides SET 
                LicenseNumber = ?, Gender = ?, Age = ?, Experience = ?,
                Specialty = ?, Introduction = ?
            WHERE GuideID = ?
        """, (*new_values[:6], guide_id), False)

        # 更新用户表
        db.execute_query("""
            UPDATE Users SET 
                Email = ?, Phone = ?, Status = ?
            WHERE UserID = (SELECT UserID FROM Guides WHERE GuideID = ?)
        """, (new_values[5], new_values[4], new_values[8], guide_id), False)

        eg.msgbox("导游信息更新成功", "成功")
    except Exception as e:
        eg.msgbox(f"更新失败: {str(e)}", "错误")